package com.juntuo.shiro;

import com.juntuo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;

/**
 * shiro 工具类
 * @author Derek
 * 
 * @date 2016/12/12
 */
public class ShiroUtil {

	private ShiroUtil() {}

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static User currentUser() {
		return (User) SecurityUtils.getSubject().getPrincipal();
	}

//	public static String currentUserId() {
//		return currentUser().getId();
//	}
//
//	public static String currentRealName() {
//		return currentUser().getRealName();
//	}

	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	/**
	 * 退出登录
	 * @param request
     */
	public static void logout(HttpServletRequest request) {
		SecurityUtils.getSubject().logout();
		//session清空
		request.getSession().invalidate();
	}

	/**
	 * 传递权限到页面js
	 * @param PermPer
	 * @param model
	 */
	public static void setModel(String PermPer, Model model, String url) {
		setModel(PermPer, model);
		model.addAttribute("url", url);
	}

	/**
	 * 设置公用js权限颗粒，增，删，改
	 * @param PermPer
	 * @param model
     */
	public static void setModel(String PermPer, Model model){
//		Subject subject = SecurityUtils.getSubject();
//		String addPerm = PermPer + Constants.SHIRO_PERM + "ADD";
//		if (subject.isPermitted(addPerm)) {
//			model.addAttribute("add", true);
//		}
//		String delPerm = PermPer + Constants.SHIRO_PERM + "DEL";
//		if (subject.isPermitted(delPerm)) {
//			model.addAttribute("del", true);
//		}
//		String updatePerm = PermPer + Constants.SHIRO_PERM + "UPDATE";
//		if (subject.isPermitted(updatePerm)) {
//			model.addAttribute("update", true);
//		}
	}

}
